import {Controller, BusinessError, ApiResponse, log} from "@codefree/badger/service";
import Auth from '../middleware/auth'

const logger = log.getLogger('yunchou');

/**
 - 继承Controller,在controller中可以使用
 - this.ctx.config
 - this.service
 - action,参数(arguments):
 - req:request，url，body
 - res:response，返回请求数据
 - next:不阻塞进程
 - ApiResponse:
 - ok
 - bizException:业务异常
 - error
 - notFound
 */
@Auth
export default class Dictionary extends Controller {
    async create() {
        const [req, res, next] = arguments;
        try {
            /**
             * key
             * value
             * description
             */

            let createBody = req.body;
            logger.debug(`${this.constructor.name}.create:${JSON.stringify(createBody)}`)
            const createdData = await this.service.dictionary.create(createBody);
            res.send(ApiResponse.ok(createdData));
        } catch (err) {
            next(err);
        }
    }

    async modify() {
        const [req, res, next] = arguments;
        try {
            let updateBody = req.body;
            await this.service.dictionary.updateDescription(updateBody.id, updateBody.description);
            res.send(ApiResponse.ok());
        } catch (err) {
            next(err);
        }
    }

    async query() {
        const [req, res, next] = arguments;
        try {
            const data = await this.to(this.service.dictionary.selfQuery(req.body), next);
            if (data) res.send(ApiResponse.ok(data));
        } catch (err) {
            next(err);
        }
    }


    async delete() {
        const [req, res, next] = arguments;
        try {
            await this.service.dictionary.delete(req.params.id, true);
            res.send(ApiResponse.ok());
        } catch (err) {
            next(err);
        }
    }
}